<script>
import ButtonList from '@/components/ButtonList'
import TableButtonList from '@/components/TableButtonList'
import WrapTable from '@/components/WrapTable'
import AjaxStore from '@/utils/store/proxyAjax'
import store from '@/mixins/treetable/src/store'
import Form from '@/components/Form'
import SearchForm from '@/components/SearchForm'
import { commonMixin } from '@/mixins/common'
import Tree from '@/components/WrapTree'
import ContainerList from '@/components/ContainerList'

export default {
  name: 'siteRolePersonFenpei',
  inject: ['Dialog', 'role'],
  props: {
    roleName: String,
    roleId: [String, Number],
    projectId: Number
  },
  mixins: [store, commonMixin],

  components: {
    SearchForm,
    WrapTable,
    Form,
    ButtonList,
    TableButtonList,
    Tree,
    ContainerList
  },
  data() {
    return {
      tree: {
        width: '280',
        height: '200',
        accordion: false,
        isShowHeader: false,
        treeMenuButtonList: [],
        treeOperateButtonList: [],
        showCheckbox: false,
        selectTree: {
          disabled: true,
          treeParams: {
            get: {
              url: '/v1/dataProvider/getGroupTreeList',
              idKey: 'id',
              nextNodeKey: 'pid'
            }
          },
          valueToLabelParams: {
            url: '/v1/dataProvider/getGroupName',
            idKey: 'groupId'
          },
          clearable: true,
          selectCodeVal: this.$store.getters.groupId || '',
          selectCodeKey: 'groupId',
          visibleChangeLoad: true
        },
        emptyTopNode: {
          expanded: true,
          id: '',
          leaf: false,
          text: '部门树'
        },
        nextNodeKey: 'node',
        idKey: 'deptId',
        search: {
          searchKey: 'deptName'
        },
        title: '',
        getNextChildNode: this.getNextNode,
        delNode: this.delNode
      },
      pidKey: 'pid',
      nodeCheckedKey: 'checked',
      nodeChildrenKey: 'children',
      nodeLeafKey: 'leaf',
      nodeIdKey: 'id',
      nodeLabelKey: 'text',

      currentNode: null,
      dialogType: '',

      labelWidth: '80px',

      // table
      limitNum: 5,
      groupId: '',

      selectedList: [],
      containerList: [],
      currentRoleKey: '当前角色',
      currentRoleName: '',
      idKey: 'deptId',
      labelKey: 'userId',
      allPath: '',
      pUserId: '',
      getAllPathUrl: '/v1/yq/common/getAllPath',
      getNextNodeUrl: '/v1/dataProvider/getDeptmentTreeList',
      getNodeInfoUrl: '/v1/sys/deptment/findById',
      store: new AjaxStore({
        url: '/v1/sys/user/getUserListByDeptId'
      }),
      columns: [
        {
          prop: 'userNo',
          label: '账号',
          sortable: true,
          'show-overflow-tooltip': true,
          'header-align': 'center'
        },
        {
          prop: 'userName',
          label: '姓名',
          sortable: true,
          'show-overflow-tooltip': false,
          'header-align': 'center',
          scopedSlots: {
            default: scope => {
              return (
                <c-popover
                  trigger='hover'
                  ref='popover'
                  on-show={this.getUserAllPath.bind(
                    this,
                    scope.row.userId,
                    scope.row.userName
                  )}
                  placement='top'
                  popper-class={this.setClassName(scope.row.userId)}>
                  {this.allPath}
                  <div slot='reference' class='name-wrapper user-name'>
                    {scope.row.userName}
                  </div>
                </c-popover>
              )
            }
          }
        },
        {
          prop: 'deptName',
          label: '部门',
          sortable: true,
          'show-overflow-tooltip': true,
          'header-align': 'center'
        }
      ]
    }
  },
  computed: {
    data: {
      set(newVal) {
        this.store._data = newVal
      },
      get(val) {
        return this.store.data
      }
    },
    total() {
      return this.store.total
    }
  },
  methods: {
    setClassName(userId) {
      this.pUserId = userId
      return `el-tooltip__popper is-dark username-popover username-${userId}-popover`
    },
    getUserAllPath(id, userName) {
      return this.request({
        url: this.getAllPathUrl,
        method: 'get',
        params: { userId: id }
      })
        .then(({ success, message }) => {
          if (success) {
            this.$nextTick(() => {
              const popover = document.getElementsByClassName(
                `username-${id}-popover`
              )[0]
              popover.classList.remove('el-popover')
              popover.classList.remove('el-popper')
            })
            this.allPath = message
          } else {
            this.allPath = userName
          }
        })
        .catch(err => {
          console.log(err)
        })
    },
    handleTreeSubSelect(val) {
      val && (this.groupId = val)
      !val && (this.groupId = '')
    },
    handleUserDel(data) {
      for (let i = 0; i < this.store.data.length; ++i) {
        if (data.userId === this.store.data[i].userId) {
          this.$refs.table.toggleRowSelection(this.store.data[i], false)
          break
        }
      }
      for (let i = 0; i < this.containerList.length; ++i) {
        if (data.userId === this.containerList[i].userId) {
          this.containerList.splice(i, 1)
          break
        }
      }
    },
    handleSelect(selection, row) {
      let flag = false
      for (let i = 0; i < selection.length; ++i) {
        if (row.userId === selection[i].userId) {
          flag = true
          break
        }
      }
      if (!flag) {
        for (let i = 0; i < this.containerList.length; ++i) {
          if (row.userId === this.containerList[i].userId) {
            this.containerList.splice(i, 1)
            break
          }
        }
      }
    },
    handleSelectAll(selection) {
      if (selection.length === 0) {
        for (let i = 0; i < this.store.data.length; ++i) {
          for (let j = 0; j < this.containerList.length; ++j) {
            if (this.store.data[i].userId === this.containerList[j].userId) {
              this.containerList.splice(j, 1)
              break
            }
          }
        }
      }
    },
    _getFenpeiUserInfo() {
      this.role
        .getFenpeiUserInfo({ roleId: this.role.roleId })
        .then(res => {
          if (res.success) {
            this.currentRoleName = this.roleName
            this.containerList = res.data
            this.handleCheckCheckbox()
          } else {
            this.$message({
              type: 'error',
              message: '获取已分配人员信息失败!'
            })
            this.dialogType = ''
          }
        })
        .catch(error => {
          console.log(error)
        })
    },
    handleSelectionChange(val) {
      this.selectedList = val
      for (let i = 0; i < this.selectedList.length; ++i) {
        let flag = false
        for (let j = 0; j < this.containerList.length; ++j) {
          if (this.containerList[j].userId === this.selectedList[i].userId) {
            flag = true
            break
          }
        }
        !flag ? this.containerList.push(this.selectedList[i]) : ''
      }
    },
    handleReturnSelectedList() {
      return this.containerList
    },
    handleEmptySelectedList() {
      this.containerList = []
      this.selectedList = []
      this.$refs.searchInput.clear()
      this.$refs.table.clearSelection()
    },
    handleNodeCheck(node) {
      if (node) {
        this.currentNode = node
        this.store._searchParams = {}
        this.store._searchParams['q_' + this.idKey] = node.data[this.nodeIdKey]
        this.$refs.table.load(1, this.store.limit)
        this.selectedList = this.containerList
        // window.eventBus.$emit('handleCheckboxSelect', this.containerList)
      }
    },
    handleCheckCheckbox() {
      this.$nextTick(() => {
        for (let i = 0; i < this.containerList.length; ++i) {
          for (let j = 0; j < this.store.data.length; ++j) {
            if (this.containerList[i].userId === this.store.data[j].userId) {
              this.$refs.table.toggleRowSelection(this.store.data[j], true)
              break
            }
          }
        }
      })
    },
    handleInputClick(ev, val) {
      const params = {}
      if (this.$refs.tree.currentNode) {
        params.q_deptId = this.$refs.tree.currentNode.key
        params.q_name = val
        this.store._searchParams = params
        this.$refs.table.load(1, this.store.limit)
      }
    },
    handleTreeEmpty() {
      this.data = []
    },
    getData({ page, limit }) {
      console.log(this.store)
      this.store && (this.store._searchParams.q_groupId = this.groupId)
      this.store.read({ projectId: this.projectId, start: page, limit: limit })
    },
    // handleNodeCheck(node) {
    //   if (node) {
    //     this.currentNode = node
    //     this.store._searchParams = {}
    //     this.store._searchParams['q_' + this.idKey] = node.data[this.nodeIdKey]
    //     this.$refs.table.load(1, this.store.limit)
    //   }
    // },

    // eslint-disable-next-line
    renderWrapTable(h) {
      return (
        <WrapTable
          ref='table'
          autoLoad={false}
          getData={this.getData}
          total={this.total}
          data={this.data}
          fields={this.columns}
          limitNum={this.limitNum}
          tooltip-effect='dark'
          paginationLayout='->, prev, pager, next'
          border
          stripe
          default-sort={{ prop: 'funId', order: 'descending' }}
          on-selection-change={this.handleSelectionChange}
          on-select={this.handleSelect}
          on-select-all={this.handleSelectAll}>
          <SearchForm
            items={this.searchFields}
            props-model={this.searchModel}
            slot='searchPanel'
            ref='searchForm'>
            <ButtonList
              operateBtnList={this.searchBtnList}
              props-model={this.searchModel}></ButtonList>
          </SearchForm>

          <c-row slot='toolPanel' class='toolPanel'>
            <ButtonList operateBtnList={this.toolPanelBtnList}></ButtonList>
          </c-row>
        </WrapTable>
      )
    },
    // eslint-disable-next-line
    renderTree(h) {
      return (
        <Tree
          ref='tree'
          tree={this.tree}
          on-check-treeNode={this.handleNodeCheck}
          on-tree-empty={this.handleTreeEmpty}
          on-tree-subSelect={this.handleTreeSubSelect}></Tree>
      )
    },
    // eslint-disable-next-line
    renderSearch(h) {
      return (
        <c-input
          ref='searchInput'
          class='search-input'
          placeholder='输入账号或姓名搜索'
          size='small'
          on-input={event => {
            this.searchInput = event
          }}
          nativeOnKeydown={ev => {
            ev.keyCode === 13
              ? this.handleInputClick(ev, this.searchInput)
              : null
          }}>
          <i
            slot='suffix'
            class='el-input__icon el-icon-search'
            on-click={ev => this.handleInputClick(ev, this.searchInput)}></i>
        </c-input>
      )
    }
  },
  render(h) {
    return (
      <div class='rolePersonFenpei'>
        <div class='title'>
          {this.currentRoleKey}: {this.currentRoleName}
        </div>
        <div class='two-columns'>
          <div class='left'>{this.renderTree(h)}</div>
          <div class='right right-form'>
            {this.renderSearch(h)}
            {this.renderWrapTable(h)}
          </div>
        </div>
        <div class='role-bottom'>
          <ContainerList
            ref='containerList'
            title='已分配人员'
            equal={(a, b) => {
              return a.userId === b.userId
            }}
            formater={item => {
              return item.deptName + '-' + item.userName
            }}
            value={this.containerList}
            on-deleteItem={this.handleUserDel}></ContainerList>
        </div>
      </div>
    )
  },
  watch: {
    'Dialog.visible': {
      immediate: true,
      handler(val) {
        val && this._getFenpeiUserInfo()
        val &&
          this.$nextTick(() => {
            this.$refs.tree.load()
          })
      }
    },
    data: {
      // immediate: true,
      handler() {
        this.handleCheckCheckbox()
      }
    },
    projectId(nVal) {
      this.projectId = nVal
    }
  }
}
</script>

<style lang="scss">
.rolePersonFenpei {
  height: 460px;
  box-sizing: border-box;
  .title {
    font-size: 14px;
    padding-bottom: 5px;
  }
  .two-columns {
    height: 337px;
    margin-top: 5px;
    box-sizing: border-box;
    .left {
      padding-left: 0;
      height: 100%;
      .panel {
        width: 200px !important;
        .search {
          margin: 0 0 5px 0;
        }
      }
      .is-empty.el-scrollbar {
        margin-top: 5px;
        max-height: 225px !important;
        height: 225px !important;
        .el-select-dropdown__list {
          padding-top: 0;
          .expand-tree {
            margin-top: 0;
          }
        }
      }
      .header {
        display: none;
      }
    }
    .right {
      box-sizing: border-box;
      border-left: 1px solid #dddfe7;
      padding-left: 20px;
      .search-input {
        float: right;
        width: 55%;
        margin-bottom: 8px;
        .el-input__suffix {
          cursor: pointer;
          border-left: 1px solid #e6e6e6;
        }
      }
      .user-name {
        overflow: hidden;
        white-space: nowrap;
        text-overflow: ellipsis;
      }
    }
    .wrap-table {
      margin-top: 0;
      .searchPanel {
        display: none;
      }
      .toolPanel {
        display: none;
      }
      .pagination {
        margin: 4px 0 0;
      }
    }
  }
  .role-bottom {
    height: 112px;
  }
}
.username-popover {
  .popper__arrow {
    display: none;
  }
}
</style>
